package com.gongpingjialoan.activity.car;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseScrollFragment;
import com.gongpingjialoan.activity.main.LoginActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.adapter.car.DisountCarDetailAdapter;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.bean.car.PlatPrice;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class SecondCarFragment extends BaseScrollFragment implements OnPageChangeListener, OnClickListener {


    private static final int REQUEST_PAYDETAIL = 101;
    private View view;

    private ViewPager viewPager;

    private RelativeLayout flyPagerGuidLayout;

    private String[] mProductImgsUrls;

    private TextView titleTextView, priceTextView, timeTextView;

    private TimeCount downTimer;

    private LinearLayout other_linearLayout;

    private List<PlatPrice> platPrices;


    private ViewGroup viewGroup;

    private String car_id = "";

    private TextView mTextViewYear, mTextViewCity, mTextViewMile, mTextViewVolume, mTextViewControl, mTextViewColor;

    private TextView mTextViewCompany;

    private TextView mandatory_insurance;

    private TextView mTextViewRegion;

    private TextView examine_insurance;

    private TextView mTextViewDescription, shoufuTextView, yuefuTextView;

    private ImageView img;

    private TextView tv_car_source_type;

    private TextView  appiontTextView;

    private TextView imageselectTextView, imageAllTextView;
    private String phone = "";
    private String status;

    private static final int LOGINING_FORSEECAR = 0X00393;
    private static final int SEE_CAR_REQUEST = 0X00394;

    private View reportView;

    private LinearLayout mPayCarLl;
    private String mTitle;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable
    ViewGroup container, @Nullable Bundle savedInstanceState) {
        isScrollPage = true;
        view = inflater.inflate(R.layout.usedcar_item, container, false);
        initView();
        return view;
    }


    private void initView() {
        shoufuTextView = (TextView) view.findViewById(R.id.shoufu);
        yuefuTextView = (TextView) view.findViewById(R.id.yuefu);
        reportView = view.findViewById(R.id.report_view);
        imageselectTextView = (TextView) view.findViewById(R.id.iamge_select);
        imageAllTextView = (TextView) view.findViewById(R.id.iamge_all);
        appiontTextView = (TextView) view.findViewById(R.id.appiond_id);
        viewGroup = (ViewGroup) view.findViewById(R.id.main);
        titleTextView = (TextView) view.findViewById(R.id.car_title);
        priceTextView = (TextView) view.findViewById(R.id.car_price);
        timeTextView = (TextView) view.findViewById(R.id.time_dealine);
        other_linearLayout = (LinearLayout) view.findViewById(R.id.content);
        img = (ImageView) view.findViewById(R.id.img_d);
        mTextViewYear = (TextView) view.findViewById(R.id.car_year);
        mTextViewCity = (TextView) view.findViewById(R.id.car_city);
        mTextViewMile = (TextView) view.findViewById(R.id.car_mile);
        mTextViewVolume = (TextView) view.findViewById(R.id.car_volume);
        mTextViewControl = (TextView) view.findViewById(R.id.car_control);
        mTextViewColor = (TextView) view.findViewById(R.id.car_color);
        mTextViewCompany = (TextView) view.findViewById(R.id.car_comp);
        mandatory_insurance = (TextView) view.findViewById(R.id.mandatory_insurance);
        mTextViewRegion = (TextView) view.findViewById(R.id.car_region);
        examine_insurance = (TextView) view.findViewById(R.id.examine_insurance);
        mTextViewDescription = (TextView) view.findViewById(R.id.car_meta);
        tv_car_source_type = (TextView) view.findViewById(R.id.tv_car_source_type);
        flyPagerGuidLayout = (RelativeLayout) view.findViewById(R.id.flyPagerGuidLayout);
        viewPager = (ViewPager) view.findViewById(R.id.guidePages);
        Utils.flySetViewPagerDuration(viewPager, 1000);
        viewPager.addOnPageChangeListener(this);

        reportView.setOnClickListener(this);
        mPayCarLl = (LinearLayout) view.findViewById(R.id.pay_car_ll);

        //  gridView.setOnItemClickListener(this);
    }


    private boolean isOnline = true;

    public void loadDataSuccess(JSONObject json) {
        try {
            JSONArray imgs = json.getJSONArray("imgs");
            initViewPage(imgs);
            initTitle(json);
            initGridView(json);
            viewGroup.setVisibility(View.VISIBLE);
        } catch (Exception e) {

        }
    }


    private void initTitle(JSONObject json) throws Exception {
        mTitle = json.getString("title");
        titleTextView.setText(mTitle);
        priceTextView.setText(json.getString("promo_price"));
        mTextViewYear.setText(json.getString("year"));
        mTextViewCity.setText(json.getString("city"));
        phone = json.getString("phone");
        DecimalFormat df = new DecimalFormat("0.00");
        JSONObject loan_info = json.getJSONObject("loan_info");
        if (loan_info != null && loan_info.has("down_payments") && loan_info.has("monthly_payments")) {
            yuefuTextView.setVisibility(View.VISIBLE);
            shoufuTextView.setVisibility(View.VISIBLE);
            String price = df.format(loan_info.getInt("down_payments") / 10000d);
            String sf = "首付" +  price + "万,";
            shoufuTextView.setText(Utils.changeColor(getActivity(), sf, 2, 2 + price.length(), R.color.text_orange_dark));
            String price1 = loan_info.getInt("monthly_payments") + "";
            String sf1 = "月供" + price1 + "元 (" + loan_info.getInt("months") + "期)";
            yuefuTextView.setText(Utils.changeColor(getActivity(), sf1, 2, 2 + price1.length(), R.color.text_orange_dark));
        }else{
            yuefuTextView.setVisibility(View.GONE);
            shoufuTextView.setVisibility(View.GONE);
        }

        String mMile = json.getString("mile");
        if (mMile.length() == 0 || mMile.equals("None") || mMile.equals("null"))
            mTextViewMile.setText("-");
        else
            mTextViewMile.setText(mMile + "万公里");

        String mVolume = json.getString("volume");
        if (mVolume.length() == 0 || mVolume.equals("None") || mVolume.equals("null"))
            mTextViewVolume.setText("-");
        else
            mTextViewVolume.setText(mVolume + "L");

        String mControl = json.getString("control");
        if (mControl.length() == 0 || mControl.equals("None") || mControl.equals("null"))
            mTextViewControl.setText("-");
        else
            mTextViewControl.setText(mControl);

        String mColor = json.getString("color");
        if (mColor.length() == 0 || mColor.equals("None") || mColor.equals("null"))
            mTextViewColor.setText("-");
        else
            mTextViewColor.setText(mColor);

        String mCompany = json.getString("company_name");
        if (mCompany.length() == 0 || mCompany.equals("None") || mCompany.equals("null"))
            mTextViewCompany.setText("-");
        else
            mTextViewCompany.setText(mCompany);

        String mRegion = json.getString("region");
        if (mRegion.length() == 0 || mRegion.equals("None") || mRegion.equals("null"))
            mTextViewRegion.setText("-");
        else
            mTextViewRegion.setText(mRegion);

        String mDescription = json.getString("description");
        if (mDescription.length() == 0 || mDescription.equals("None") || mDescription.equals("null"))
            mTextViewDescription.setText("-");
        else
            mTextViewDescription.setText(mDescription);

        if (json.getString("mandatory_insurance").equals("")) {
            mandatory_insurance.setText("-");
        } else {
            mandatory_insurance.setText(json.getString("mandatory_insurance"));
        }

        if (json.getString("examine_insurance").equals("")) {
            examine_insurance.setText("-");
        } else {
            examine_insurance.setText(json.getString("examine_insurance"));
        }


        car_id = json.getString("id");
        String order_status = json.getString("order_status");
        if ("ordered".equals(order_status)) {
            TextView textView = (TextView) view.findViewById(R.id.pag_tv);
            textView.setText("已交定金");
            mPayCarLl.setBackgroundColor(Color.parseColor("#5A5A5A"));
        }else if("available".equals(order_status)){
            mPayCarLl.setOnClickListener(this);
        }else{
            mPayCarLl.setVisibility(View.GONE);
        }

        isOnline = json.getBoolean("online_status");


        long time = Long.parseLong(json.getString("remain_time"));
        status = json.getString("car_status");

        if (time == 0 || "end".equals(status) || "success".equals(status)) {
            resetime();
        } else {
            timeTextView.setText(Utils.dateDiff(time));
            downTimer = new TimeCount(time * 1000, 1000);
            downTimer.start();
        }

        if (isOnline) {
            if ("appointed".equals(status)) {
                enableButton();
            }
        } else {
            appiontTextView.setVisibility(View.VISIBLE);
            appiontTextView.setText("已下架");
        }
    }


    public void appiontSuccess() {
        status = "appointed";
        appiontTextView.setVisibility(View.VISIBLE);
    }

    private void enableButton() {
        appiontTextView.setVisibility(View.VISIBLE);
    }





    private void resetime() {
        img.setVisibility(View.GONE);
        timeTextView.setVisibility(View.GONE);
    }


    private void initGridView(JSONObject json) throws Exception {
        JSONArray jsonArray = json.getJSONArray("other_plat_list");
        boolean isDealer_tag = json.getBoolean("dealer_tag");
        if (isDealer_tag) {
            tv_car_source_type.setVisibility(View.VISIBLE);
        } else {
            tv_car_source_type.setVisibility(View.GONE);
        }

        platPrices = new ArrayList<>();
        int length = jsonArray.length();
        for (int i = 0; i < length; i++) {
            PlatPrice platPrice = new PlatPrice();
            JSONObject item = (JSONObject) jsonArray.get(i);
            //String []items = item.split(",");
            platPrice.setName(item.getString("plat"));
            platPrice.setId(item.getString("id"));
            platPrice.setUri(item.getString("url"));
            platPrice.setPrice(item.getString("price"));
            platPrice.setDiscount(item.getString("discount"));
            platPrice.setTitle(item.getString("title"));
            platPrices.add(platPrice);
        }
//       MyGridViewAdapter gridViewAdapter = new MyGridViewAdapter();
//       gridView.setAdapter(gridViewAdapter);
        addOtherPrice();
    }


    private void addOtherPrice() {
        int size = platPrices.size();
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.discount_other_item, null);
                TextView title = (TextView) view.findViewById(R.id.title);
                TextView discount = (TextView) view.findViewById(R.id.sheng_id);
                TextView price = (TextView) view.findViewById(R.id.car_price);
                TextView noimage = (TextView) view.findViewById(R.id.noimage);
                ImageView imageView = (ImageView) view.findViewById(R.id.iv_item);
                title.setText(platPrices.get(i).getTitle());
                discount.setText(platPrices.get(i).getDiscount() + "元");
                price.setText(platPrices.get(i).getPrice());
                int id = platPrices.get(i).getImageId();
                if (id == 0) {
                    noimage.setVisibility(View.VISIBLE);
                    noimage.setText(platPrices.get(i).getName());
                    imageView.setVisibility(View.GONE);
                } else {
                    noimage.setVisibility(View.GONE);
                    imageView.setImageBitmap(Utils.readBitMap(getActivity(), platPrices.get(i).getImageId()));
                }
                other_linearLayout.addView(view, i);
                view.setTag(platPrices.get(i));
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PlatPrice platPrice = (PlatPrice) v.getTag();
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), CarBuyDetailActivity.class);
                        intent.putExtra("typevalue", platPrice.getId());
                        intent.putExtra("type", "other_plat");
                        startActivity(intent);
                    }
                });
            }
        } else {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.no_other_layout, null);
            other_linearLayout.addView(view, 0);
        }

    }


    /**
     * 初始化图片
     *
     * @param imgs
     * @throws JSONException
     */
    private void initViewPage(JSONArray imgs) throws JSONException {
        mProductImgsUrls = new String[imgs.length()];
        for (int i = 0; i < imgs.length(); i++) {
            mProductImgsUrls[i] = (String) imgs.get(i);
        }

        if (mProductImgsUrls.length == 0) {
            flyPagerGuidLayout.setVisibility(View.GONE);
            viewPager.setAdapter(new DisountCarDetailAdapter(mProductImgsUrls, this, false));
        } else {
            imageAllTextView.setText("/" + mProductImgsUrls.length);
            flyPagerGuidLayout.setVisibility(View.VISIBLE);
            viewPager.setAdapter(new DisountCarDetailAdapter(mProductImgsUrls, this, true));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (downTimer != null) {
            downTimer.cancel();
            downTimer = null;
        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int index) {
        imageselectTextView.setText(index + 1 + "");
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            resetime();
        }

        @Override
        public void onTick(long millisUntilFinished) {
            timeTextView.setText(Utils.dateDiff(millisUntilFinished / 1000));
        }
    }


    @Override
    public void onClick(View arg0) {
         if (arg0 == reportView) {
            DiscountDetailActivity discountDetailActivity = (DiscountDetailActivity) getActivity();
            discountDetailActivity.report();
        }else if(arg0 == mPayCarLl){
            if(TextUtils.isEmpty(car_id)){
                return;
            }
            if (GPJApplication.getInstance().isLogin()) {
                gotoPayDatail();
            } else {
                Intent intent = new Intent();
                intent.setClass(getActivity(), LoginActivity.class);
                startActivityForResult(intent, REQUEST_PAYDETAIL);
            }

        }
    }

    private void gotoPayDatail() {
        Intent i = new Intent(getActivity(),PayDetailActivity.class);
        i.putExtra("action_type", "recommend_detail_detailCarOrder");
        StepMonitor.getInstance().addMonitor(new Monitor("click", "recommend_detail_detailCarOrder", System.currentTimeMillis(), 1f));
        i.putExtra("carName",mTitle);
        i.putExtra("car_id",car_id);
        i.putExtra("type","promo_car_ordered_record");
        startActivity(i);
    }

    private void gotoSeeCar() {
        StepMonitor.getInstance().addMonitor(new Monitor("click", "recommend_detail_appoint", System.currentTimeMillis(), 1f));
        Intent intent = new Intent(getActivity(), SeeCarActivity.class);
        intent.putExtra("car_id", car_id);
        startActivityForResult(intent, SEE_CAR_REQUEST);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == LOGINING_FORSEECAR) {
                gotoSeeCar();
            } else if (requestCode == SEE_CAR_REQUEST) {
                Toast.makeText(getActivity(), "预约成功！", Toast.LENGTH_SHORT).show();
                appiontSuccess();
                if (MainActivity.main != null)
                    MainActivity.main.mRecomendDiscountFragment.updateDiscountListItem();
            }else if (requestCode == REQUEST_PAYDETAIL) {
                gotoPayDatail();
            }
        }
    }


}
